﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization;
using log4net;
using Needle.Bus.Messages;
using Needle.Utils;

namespace Needle.Bus.Engine.MessageHandlers
{
    public class MessageDumper : IMessageHandler
    {

        private DirectoryInfo _folder;
        private ILog _log;
        private NetDataContractSerializer _serializer;

        public MessageDumper()
        {
            _log = LogManager.GetLogger(GetType());
            _serializer = new NetDataContractSerializer(new StreamingContext(StreamingContextStates.Persistence));
        }

        public void Initialize()
        {
        }

        public void Process(IMessage message)
        {
            try
            {
                using (var stream = File.OpenWrite(GetFileName()))
                {
                    _serializer.Serialize(stream, message);
                }
            }
            catch (Exception ex)
            {
                _log.InfoFormat("Error dumping message: " + message.ToString(), ex);
            }
        }

       public void Process(IList<IMessage> messages)
        {
            try
            {
                using (var stream = File.OpenWrite(GetFileName()))
                {
                    _serializer.Serialize(stream, messages);
                }
            }
            catch (Exception ex)
            {
                _log.InfoFormat("Error dumping messages.", ex);
            }
        }

       int uniqueId = 0;
       private string GetFileName()
       {
           uniqueId++;
           string timestamp = DateTime.UtcNow.ToString("u");
           var fileName = FileSystem.ReplaceInvalidFilenameChars(timestamp + uniqueId.ToString() + ".xml", '_');
           return Path.Combine(_folder.FullName, fileName);
       }

       public string Folder
       {
           get { return _folder.FullName; }
           set
           {
               _folder = new DirectoryInfo(value);
               if (!_folder.Exists)
                   _folder.Create();
           }
       }

        public void Dispose()
        {
        }
    }
}
